//
//  CCDatePickView.swift
//  TCCKit
//
//  Created by liujianlong on 2022/11/1.
//

import UIKit
#if canImport(TCC_String)
import TCC_String
#endif
#if canImport(TCC_Date)
import TCC_Date
#endif
#if canImport(TCC_Extension)
import TCC_Extension
#endif
@objc open class CCDatePickView: UIView {
    open var date:DateComponents?
    open var selectDate:DateComponents?
    open var block:((_ stamp:NSInteger)->Void)?
    private func stam(_ day:Int)->NSInteger {
        let str = String(format:"%d/%d/%d",self.selectDate!.year!,self.selectDate!.month!,day)
        return Int(NSDate.tranToStamp(str, "yyyy/MM/dd")) ?? 0
    }
    open  var stamp:NSInteger = 0{
        didSet{
            self.date = NSDate.dateOfStamp(oldValue)
            self.selectDate = NSDate.dateOfStamp(oldValue)
            self.pickView.reloadAllComponents()
            self.pickView.selectRow(self.date?.year ?? 0 , inComponent: 0, animated: false)
            self.pickView.selectRow(self.date?.month ?? 1 - 1, inComponent: 1, animated: false)
            self.pickView.selectRow(self.date?.day ?? 1 - 1, inComponent: 2, animated: false)
        }
    }
    lazy private var pickView:UIPickerView = {
        let pick = UIPickerView()
        pick.delegate = self
        pick.dataSource = self
        return pick
    }()
    
}
//MARK: - UIPickerViewDataSource
extension CCDatePickView:UIPickerViewDataSource{
    open func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0{
            return 30
        }else if component == 1{
            return 12
        }else{
            return NSDate.numOfMonth(self.stam(1))
        }
    }
    
}
//MARK: - UIPickerViewDataSource

extension CCDatePickView:UIPickerViewDelegate{
    open func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return 100
    }
    open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0{
            self.selectDate?.year = (self.date?.year)! - row
        }else if component == 1{
            self.selectDate?.month = row + 1
        }else{
            self.selectDate?.day = 1
        }
        pickerView.reloadComponent(2)
        self.block?(self.stam(self.selectDate!.day!))
    }
    open func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let lbl = UILabel()
        lbl.textAlignment = .center
        lbl.textColor = .black
        if component == 0{
            lbl.text = String(format:LS("%d年"), (self.date?.year)! - row)
        }else if component == 1{
            lbl.text = String(format:LS("%d月"), row + 1)
        }else{
            lbl.text = String(format:LS("%d日"), row + 1)
        }
        return lbl
    }
}
